﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Traceability.Commont.Domains.AnimalsDomainFiles;
using Traceability.Commont.DTOs.CommontFiles;
using Traceability.Commont.Infrastructures.Interfaces;

namespace U.Enterprise.Api.Applications.AdmissionRegistrationFile
{
    /// <summary>
    /// 企业添加
    /// </summary>
    public class ApproachCreateHander : IRequestHandler<ApproachCreateCommand, Resqults>
    {
        private readonly IMapper mapper;
        private readonly IBateRepository<Approach> approach;
        private readonly IBateRepository<Shopping> shop;

        public ApproachCreateHander(IMapper mapper, IBateRepository<Approach> approach, IBateRepository<Shopping> shop)
        {
            this.mapper = mapper;
            this.approach = approach;
            this.shop = shop;
        }

        public async Task<Resqults> Handle(ApproachCreateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                Resqults res = new Resqults() { Code = 0 };
                Approach info = mapper.Map<Approach>(request);
                if (request.Pid == 0)
                {
                    res.Code = await approach.Add(info);
                    if (res.Code > 0)
                    {
                        res.Messges = "添加成功";
                        var shopInfo = await shop.GetAll().Where(x => x.ShoppingDesignationName == request.ShoppingDesignationid).FirstOrDefaultAsync();
                        if (shopInfo == null)
                        {
                            Shopping shopping = new Shopping()
                            {
                                ShoppingDesignationName = request.ShoppingDesignationid,
                                Unit="公斤",
                                Tablereport="无",
                                Sku="公斤"
                            };
                            res.Code += await shop.Add(shopping);
                        }
                    }
                    else
                    {
                        res.Messges = "添加失败";
                    }
                }
                else
                {
                    var appInfo = await approach.GetAll().FirstOrDefaultAsync(x => x.ApproachBatch == info.ApproachBatch);
                    appInfo.Approachnum += info.Approachnum;
                    res.Code += await approach.Update(appInfo);
                    if (res.Code > 0)
                    {
                        res.Messges = "合并成功";
                    }
                    else
                    {
                        res.Messges = "合并失败";
                    }
                }

                return res;

            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
